package com.zsw.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.zsw.entity.User;
import com.zsw.form.LoginForm;
import com.zsw.service.UserService;
import com.zsw.util.JwtUtil;
import com.zsw.util.Result;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    @Autowired
    private RedisTemplate redisTemplate;  //需要在配置文件中配置一下redis

    @Autowired
    UserService userService;

    @Autowired
    JwtUtil jwtUtil;

    /**
     * 生成验证码
     *
     * @return
     */
    @GetMapping("/captcha")
    public Result getCode() {
        //使用工具生成验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        String code = specCaptcha.text().toLowerCase();
        String uuid = IdUtil.simpleUUID();
        //将uuid和code保存在redis中     key   value  保存时间       秒
        redisTemplate.opsForValue().set(uuid, code, 120, TimeUnit.SECONDS);
        Map<String, Object> map = new HashMap<>();
        //uuid 将验证码存放在redis中的key
        map.put("uuid", uuid);
        map.put("captcha", specCaptcha.toBase64());
        map.put("code", code);
        return Result.ok().put("data", map);
    }

    @PostMapping("/login")
    public Result loign(@RequestBody LoginForm form, HttpSession session) {
        String paramUUID = form.getUuid();
        //获取验证码，1.前端会传过来一个uuid根据uuid去redis中获取验证码  2.前端传过来的验证码在
        String redisCode = (String) redisTemplate.opsForValue().get(paramUUID);
        //判断验证码是否有效
        if (redisCode == null) {
            return Result.ok().put("status", "fial").put("data", "验证码失效");
        }
        String code = form.getCaptcha();
        if (!redisCode.equals(code)) {
            return Result.ok().put("status", "fial").put("data", "验证码错误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", form.getUsername());
        User user = this.userService.getOne(queryWrapper);
        if (user == null) {
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        String password = SecureUtil.sha256(form.getPassword());
        if (!password.equals(user.getPassword())) {
            return Result.error("密码错误");
        }
        //验证用户是否可用
        if (user.getStatus() == 0) {
            return Result.error("账号已被锁定，请联系管理员");
        }
        //登录成功
        //存入session
        session.setAttribute("user", user);
        //登录成功之后，会给你一个token(令牌)，
        // 之后你的每一次操作都需要这个令牌(没有的话，你就得重新登录)
        //创建token，根据userId 生成token
        String token = this.jwtUtil.createToken(String.valueOf(user.getUserId()));
        //存入redis中
        this.redisTemplate.opsForValue().set("communityuser-" + user.getUserId(), token, jwtUtil.getExpire());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtil.getExpire());
//        LogAspect.user = user;
        return Result.ok().put("data", map);
    }
    @GetMapping("/checkToken")
    public Result checkToken(HttpServletRequest request){
        //从request请求体中，获取token然后，然后比较
        String token = request.getHeader("token");
        boolean result = this.jwtUtil.checkToken(token);
        if(result) return Result.ok().put("status", "ok");
        return Result.ok().put("status", "error");
    }


}
